package com.wanbatv.wanba.jianshencao.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.squareup.picasso.Picasso;
import com.wanbatv.wanba.jianshencao.R;
import com.wanbatv.wanba.jianshencao.util.AppUtil;
import com.wanbatv.wanba.jianshencao.util.Crypto;
import com.wanbatv.wanba.jianshencao.util.Util;
//import com.wanbatv.wanba.jianshencao.util.WanbaMediaPlayer;
import com.wanbatv.wanba.jianshencao.utils.Product;
//import com.wanbatv.wanbaott.WanbaPlayer;
//import com.wanbatv.wanbaott.WanbaPlayerCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.ffcs.itvpay.ItvPayTask;
//import io.vov.vitamio.MediaPlayer;
//import io.vov.vitamio.Vitamio;
// import tv.danmaku.ijk.media.player.AndroidMediaPlayer;
// import tv.danmaku.ijk.media.player.IMediaPlayer;
// import tv.danmaku.ijk.media.player.IjkMediaPlayer;

/**
 * Created by ricardo on 2017/3/10.
 */
public class ShowActivity extends Activity implements SurfaceHolder.Callback, MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener {
    private LinearLayout preview;
    private ImageView stop;
    private ImageView backward;
    private ImageView speed;
    private TextView currTime;
    private ViewGroup.LayoutParams lp;
//    private ImageMove imgmove;
    private SeekBar seek;
    public int i=1;
    private SurfaceView surface;
    private int current;
    private int alltime;
    private Intent intent;
    private String playurl;
    JSONArray zhifuArray =null;
    String orderInfo=null;
    private final int MSG_PROGRESS=100;
    private final int MSG_HIDE=111;
    private final int MSG_STATE=112;
    private final int MSG_PREPARED = 113;
    private final int MSG_SEEK = 114;
    private boolean PRETAG=false;
    private SurfaceHolder holder;
    private int time=0;

    private boolean isPlaying = false;

    private static final int MSG_FF = 1001;
    private static final int MSG_BACK = 1002;

    private boolean isSeeking = false;

    Handler seekHandler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_SEEK:
                    try {
                        if (mediaPlayer != null) {
                            mediaPlayer.seekTo(seek.getProgress());
                        }
                        seekHandler.removeMessages(MSG_SEEK);
                        isSeeking = false;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    };

    Handler handler=new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(Message msg) {
            if (mediaPlayer == null) {
                handler.removeMessages(MSG_STATE);
                handler.removeMessages(MSG_PROGRESS);
                handler.removeMessages(MSG_HIDE);
                handler.removeMessages(MSG_PREPARED);
                handler.removeMessages(MSG_SEEK);
                handler.removeMessages(MSG_FF);
                handler.removeMessages(MSG_BACK);
                return;
            }

            switch (msg.what){
                case MSG_FF: // 快进
                    try {
                        int duration = seek.getMax();
                        int currentPosition = seek.getProgress() + 2000;
                        if (currentPosition >= duration) {
                            mediaPlayer.stop();
                            isPlaying = false;
                        } else {
                            seek.setProgress(currentPosition);
                        }
                        if (seekHandler.hasMessages(MSG_SEEK)) {
                            seekHandler.removeMessages(MSG_SEEK);
                        }
                        seekHandler.sendEmptyMessageDelayed(MSG_SEEK, 1000);
                        isSeeking = true;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case MSG_BACK: // 快退
                    try {
                        int currentPosition = seek.getProgress();
                        int totime = 0;
                        if (currentPosition - 2000 <= 0) {
                            totime = 0;
                        } else {
                            totime = currentPosition - 2000;
                        }
                        seek.setProgress(totime);
                        if (seekHandler.hasMessages(MSG_SEEK)) {
                            seekHandler.removeMessages(MSG_SEEK);
                        }
                        seekHandler.sendEmptyMessageDelayed(MSG_SEEK, 1000);
                        isSeeking = true;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case MSG_PREPARED:
                    onPrepared(mediaPlayer);
                    handler.removeMessages(MSG_PREPARED);
                    break;
                case MSG_STATE:
                    if (mediaPlayer!=null) {
                        Log.d("ricardo","noplaying");
                        try {
                            int duration = mediaPlayer.getDuration();
                            int secondtime = duration / 1000;
                            int mintime = secondtime / 60;
                            int setime = secondtime - mintime * 60;
                            totaltime.setText(formatTime(mintime, setime));
                            seek.setMax((int) duration);
                            time=time+1000;
                            seek.setProgress(time);
                            int second = time / 1000;
                            int min = second / 60;
                            int se = second - min * 60;
                            currTime.setText(formatTime(min, se));
                            if (!PRETAG){
                                stop.setClickable(false);
                            }else{
                                stop.setClickable(true);
                            }
                            handler.sendEmptyMessageDelayed(MSG_STATE,1000);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }

                    break;
                case MSG_PROGRESS:
                    Log.d("ricardo","progress");
//                    Log.e("kevin",mediaPlayer.isPlaying()+"");
                    try {
                        if (!isSeeking) {
                            int duration = mediaPlayer.getDuration();
                            int secondtime = duration / 1000;
                            int mintime = secondtime / 60;
                            int setime = secondtime - mintime * 60;
                            totaltime.setText(formatTime(mintime, setime));
                            seek.setMax((int) mediaPlayer.getDuration());
                            per = (int) (mediaPlayer.getDuration()/100);
                            seek.setProgress((int) mediaPlayer.getCurrentPosition());
                        }
                    }catch (IllegalStateException e){
                        e.printStackTrace();
                    }

                    try {
                        int currentPosition = (int) mediaPlayer.getCurrentPosition();
                        int second = currentPosition / 1000;
                        int min = second / 60;
                        int se = second - min * 60;
                        currTime.setText(formatTime(min, se));
                        if (se>=20&&mediaPlayer!=null&&!EpgActivity.IS_DINGGOU){
                            mediaPlayer.pause();
                            zhezhao.setVisibility(View.VISIBLE);
//                            showPreview();
                            creatAlertDialog_tuichu();
                        }
                    }catch (IllegalStateException e){
                        e.printStackTrace();
                    }


                    handler.removeMessages(MSG_PROGRESS);
                    Log.d("ricardo","sendpro4");
                    handler.sendEmptyMessageDelayed(MSG_PROGRESS,1000);
                    if (mediaPlayer.isPlaying() ||
                            (mediaPlayer.getCurrentPosition() > 0 && !handler.hasMessages(MSG_HIDE))){
//                        Log.d("ShowActivity", "~~~ handleMessage send hide msg");
                        handler.sendEmptyMessageDelayed(MSG_HIDE,3000);
                    }
                    break;
                case MSG_HIDE:
                    if (preview.getVisibility()==View.VISIBLE){
                        zhezhao.setVisibility(View.INVISIBLE);
                    }

                    break;

            }

        }
    };
    private MediaPlayer mediaPlayer;
    private int per;
    private String[] imgs;
    private String[] urls;
    private String[] names;
    private RelativeLayout zhezhao;
    private TextView totaltime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        Vitamio.isInitialized(getApplicationContext());
        setContentView(R.layout.show);
        Log.d("ricardo","oncreate");
        stop = ((ImageView) findViewById(R.id.stop));
        backward = ((ImageView) findViewById(R.id.backward));
        speed = ((ImageView) findViewById(R.id.speed));
        currTime = (TextView) findViewById(R.id.currtime);
        totaltime = ((TextView) findViewById(R.id.totaltime));
        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (AppUtil.STB.Model.equals("E8205") && !PRETAG) {
                    return;
                }

                if (mediaPlayer!=null && (mediaPlayer.isPlaying() || isPlaying)){
                    mediaPlayer.pause();
                    isPlaying = false;
                    stop.setImageResource(R.drawable.newbofangfocus);
                    if (handler.hasMessages(MSG_HIDE)) {
                        handler.removeMessages(MSG_HIDE);
                    }
//                    Log.d("ShowActivity", "~~~ onClick send hide msg");
                    handler.sendEmptyMessageDelayed(MSG_HIDE,3000);
                }else if (mediaPlayer!=null && (!mediaPlayer.isPlaying() || !isPlaying)){
                    Log.d("ricardo","start");
                    mediaPlayer.start();
                    isPlaying = true;
                    stop.setImageResource(R.drawable.newzangtingfocus);
                    if (handler.hasMessages(MSG_HIDE)) {
                        handler.removeMessages(MSG_HIDE);
                    }
//                    Log.d("ShowActivity", "~~~ onClick send hide msg");
                    handler.sendEmptyMessageDelayed(MSG_HIDE,3000);
                }
            }
        });
        backward.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                handler.sendEmptyMessage(MSG_BACK);
            }
        });
        speed.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                handler.sendEmptyMessage(MSG_FF);
            }
        });
        zhezhao = ((RelativeLayout) findViewById(R.id.ui));
        intent = getIntent();
        playurl = intent.getStringExtra("playurl");
        imgs = intent.getStringArrayExtra("img");
        names = intent.getStringArrayExtra("name");
        Log.d("ricardo",imgs+"");
        urls = intent.getStringArrayExtra("url");
//        imgTime = new TextView(getApplicationContext());
//        imgTime.setBackgroundResource(R.drawable.time);
//        imgTime.setTextColor(Color.WHITE);
//        imgTime.setTextSize(20);
//        imgTime.setGravity(Gravity.CENTER);
//        imgmove = ((ImageMove) findViewById(R.id.imgmove));
//        imgmove.addView(imgTime);
//        imgTime.layout(0,10,60,50);
        surface = ((SurfaceView) findViewById(R.id.media));
        holder = surface.getHolder();
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        holder.addCallback(this);
        seek = ((SeekBar) findViewById(R.id.progress));
//        final int width = imgmove.getLayoutParams().width;
//        Log.d("ricardo",width+"width");
        seek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
//                float i=(int) (width)*progress/mediaPlayer.getDuration();
//                imgTime.layout((int)(i-50),10,(int)(i+60),50);

            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        preview = (LinearLayout) findViewById(R.id.preview);

        for (int i=0;i<imgs.length;i++){
            ShowView showView = new ShowView(getApplicationContext());
            ImageView img = (ImageView) showView.findViewById(R.id.pic);
            ImageView cover = (ImageView) showView.findViewById(R.id.cover);
            TextView txt = (TextView) showView.findViewById(R.id.text);
            txt.setText(names[i]);
            Picasso.with(getApplicationContext()).load(imgs[i]).into(img);
            preview.addView(showView);
            final int finalI = i;
//            cover.setOnFocusChangeListener(new View.OnFocusChangeListener() {
//                @Override
//                public void onFocusChange(View view, boolean b) {
//                    if (b) {
//                        scrollView.setFocusableInTouchMode(true);
//                    } else {
//                        scrollView.setFocusableInTouchMode(false);
//                    }
//                }
//            });
            cover.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    handler.removeMessages(MSG_STATE);
                    handler.removeMessages(MSG_PROGRESS);
                    handler.removeMessages(MSG_HIDE);
                    handler.removeMessages(MSG_PREPARED);
                    handler.removeMessages(MSG_SEEK);
                    handler.removeMessages(MSG_FF);
                    handler.removeMessages(MSG_BACK);
                    if (mediaPlayer!=null){
                        mediaPlayer.release();
                        mediaPlayer=null;
                    }

                    finish();
                    Intent intent = new Intent(getApplicationContext(), ShowActivity.class);
                    intent.putExtra("playurl",urls[finalI]);
                    intent.putExtra("img",imgs);
                    intent.putExtra("url",urls);
                    intent.putExtra("name",names);
                    startActivity(intent);

                }
            });
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        PRETAG=false;
        if (mediaPlayer!=null){
            mediaPlayer.release();
            mediaPlayer=null;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mediaPlayer!=null){
            mediaPlayer.release();
            mediaPlayer=null;
        }
    }

    private void chanpinbao(){
        RequestQueue rq_2 = Volley.newRequestQueue(getApplicationContext());
        final JsonObjectRequest request_2 = new JsonObjectRequest("http://61.191.46.214:8087/getapi/common/subjects/31259d2c48bec6a1ba589360c748e132?flavor="+ Product.flavor, null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        try {
                            JSONObject obj=jsonObject.getJSONObject("data");
                            JSONArray arr=obj.getJSONArray("list");
                            zhifuArray =arr;
                            //Toast.makeText(getApplicationContext(),obj+"@@",Toast.LENGTH_LONG).show();
                            dingdanhao();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(getApplicationContext(),"请求产品包超时，请检查网络并返回重试。",Toast.LENGTH_SHORT).show();

            }
        }

        ) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                PackageInfo pi= null;
                try {
                    pi = getApplicationContext().getPackageManager().getPackageInfo(getApplicationContext().getPackageName(), 0);
                    headers.put("accept", "applicationnd.wanba.wanbatv.com.wudao;version="+pi.versionName);
                    headers.put("app_version", pi.versionName);
                    headers.put("app_package_name",pi.packageName);
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }


                // MyLog.d(TAG, "headers=" + headers);
                return headers;
            }
        };
        request_2.setRetryPolicy(new DefaultRetryPolicy(30000,3,1.0f));

        rq_2.add(request_2);
    }
    private  void dingdanhao(){

        try {
            JSONObject obj = zhifuArray.getJSONObject(0);
            final   String subject=obj.getString("subject");
            final   String subjectId=obj.getString("subjectId");
            final   String price=obj.getString("price");
            //Toast.makeText(getApplicationContext(),obj+"==",Toast.LENGTH_SHORT).show();
            RequestQueue requestQueue = Volley.newRequestQueue(ShowActivity.this);
            String url="http://61.191.46.214:8087/postapi/common/wpay/getorder";
            StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST,url,
                    new Response.Listener<String>() {

                        @Override
                        public void onResponse(String response) {

                            try {

                                JSONObject objZhifubao = (JSONObject) new JSONTokener(response).nextValue();
                                //Toast.makeText(getApplicationContext(),obj_zhifubao+"  @  @  "+Util.getDeviceId(getApplicationContext()),Toast.LENGTH_LONG).show();
                                JSONObject oobj=objZhifubao.getJSONObject("data");
                                String order=oobj.getString("order");
                                orderInfo="orderId="+order+"|itvAccount="+ AppUtil.STB.UserID+"|productId=zg_wanba"+"|price=1500";
                                orderInfo=jiami(orderInfo);
                                Log.d("@ricardo@", "get subject "+objZhifubao);
                                ItvPayTask itvPayTask = new ItvPayTask(ShowActivity.this);
                                HashMap<String, String> data = new HashMap<String, String>();
                                data.put(ItvPayTask.NET_IP, "61.191.45.118");//访问地址ip 测试ip为61.191.45.116 正式为//61.191.45.118
                                data.put(ItvPayTask.NET_PORT, "7002");//访问地址端口
                                data.put(ItvPayTask.DEVICEMODEL, AppUtil.STB.Model);//机顶盒信息
                                //	data.put(ItvPayTask.RETURNURL, "http://61.191.46.214:8087/getapi/common/wpay/result/ahpay/");//同步返回地址
                                Log.d("ShowActivity", "@@@ notifyUrl " + "http://172.16.33.228:8087/postapi/common/wpay/paynotify/ahpay/"+AppUtil.STB.UserID);
                                data.put(ItvPayTask.NOTIFYURL, "http://172.16.33.228:8087/postapi/common/wpay/paynotify/ahpay/"+AppUtil.STB.UserID);//异步通知地址
                                data.put(ItvPayTask.DEVICETYPE, "hd");//机顶盒信息
                                data.put(ItvPayTask.USERAGENT, "wanba");//机顶盒信息
                                data.put(ItvPayTask.DEVICESERIALNO, AppUtil.STB.Sn);//机顶盒信息
                                data.put(ItvPayTask.IP, AppUtil.STB.IP);//机顶盒信息
                                data.put(ItvPayTask.ORDERINFO, orderInfo);//订单信息
                                data.put(ItvPayTask.PROVIDERID, "shzg");//供应商id
                                itvPayTask.pay(data);

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(getApplicationContext(),"请求订单号超时，请检查网络并返回重试。",Toast.LENGTH_SHORT).show();

                    error.printStackTrace();
                }
            }) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    PackageInfo pi= null;
                    try {
                        pi = getApplicationContext().getPackageManager().getPackageInfo(getApplicationContext().getPackageName(), 0);
                        headers.put("accept", "applicationnd.com.wanbatv.wanba.jianshencao;version="+pi.versionName);
                        headers.put("app_version", pi.versionName);
                        headers.put("app_package_name",pi.packageName);
                    } catch (PackageManager.NameNotFoundException e) {
                        e.printStackTrace();
                    }


                    // MyLog.d(TAG, "headers=" + headers);
                    return headers;
                }
                @Override
                public String getBodyContentType() {
                    return "application/x-www-form-urlencoded; charset=" + getParamsEncoding();
                }
                @Override
                protected Map<String, String> getParams() {
                    //在这里设置需要post的参数
                    HashMap<String, String> params = new HashMap<String, String>();
                    params.put("partner","");
                    params.put("subject", subject);
                    params.put("subjectid",subjectId);
                    params.put("price",price);
                    params.put("provider","ahpay");
                    params.put("stb", Util.getDeviceId(getApplicationContext()));
                    params.put("flavor", Product.flavor);

                    return params;
                }
            };
            stringRequest.setRetryPolicy(new DefaultRetryPolicy(30000,3,1.0f));
            requestQueue.add(stringRequest);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    private  String jiami(String orderInfo){

        String jiami= Crypto.TripleDES.encrypt(orderInfo, "26f545c0d092463185acdd3e2c73fdda");
//        String jiami=Crypto.TripleDES.decrypt(jiami,"36161889369a412b923af17dafb0fe88");
        return jiami;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ItvPayTask.REQUEST_ITYPAY&&resultCode==ItvPayTask.RESULT_ITVPAY) {
            String result = data.getStringExtra("result");
            //Toast.makeText(getApplicationContext(),result+"",Toast.LENGTH_LONG).show();
            //Log.d("ricardo@@",data.getStringExtra("providerId"));
            try {
                JSONObject obj=(JSONObject) new JSONTokener(result).nextValue();
                Log.d("ricardo@@@",obj+"");
                if(!obj.getString("tradeInfo").equals("") ){

                    EpgActivity.IS_DINGGOU=true;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            Log.e("huidiao",result);
        }
    }
    private AlertDialog myDialog = null;
    private void creatAlertDialog_tuichu() {

        if (hasWindowFocus()){
            if (myDialog==null){
                myDialog = new AlertDialog.Builder(ShowActivity.this).create();

                myDialog.show();

                myDialog.getWindow().setContentView(R.layout.diolag_queding);

                myDialog.getWindow()
                        .findViewById(R.id.no_iv)
                        .setOnClickListener(new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {

                                myDialog.dismiss();

                            }

                        });
                myDialog.getWindow()
                        .findViewById(R.id.yes_iv)
                        .setOnClickListener(new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                myDialog.dismiss();
                                handler.removeMessages(MSG_PROGRESS);
                                chanpinbao();

                            }

                        });
            }
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            if (event.getKeyCode() !=  KeyEvent.KEYCODE_BACK) {
                if (handler.hasMessages(MSG_HIDE)) {
                    handler.removeMessages(MSG_HIDE);
                }
                handler.sendEmptyMessageDelayed(MSG_HIDE,3000);
            }
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.d("ricardo", keyCode + "@@" + zhezhao.getVisibility() + "@@" + PRETAG);
//        if(keyCode != KeyEvent.KEYCODE_BACK){
//            if (handler.hasMessages(MSG_HIDE)) {
//                handler.removeMessages(MSG_HIDE);
//            }
//            handler.sendEmptyMessageDelayed(MSG_HIDE,3000);
////            zhezhao.setVisibility(View.VISIBLE);
//        }
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mediaPlayer != null) {
                mediaPlayer.release();
                mediaPlayer = null;
            }
            handler.removeMessages(MSG_STATE);
            handler.removeMessages(MSG_PROGRESS);
            handler.removeMessages(MSG_HIDE);
            handler.removeMessages(MSG_PREPARED);
            handler.removeMessages(MSG_SEEK);
            handler.removeMessages(MSG_FF);
            handler.removeMessages(MSG_BACK);
            finish();
            return true;
        } else if (keyCode == 23) {
//            if (handler.hasMessages(MSG_HIDE)) {
//                handler.removeMessages(MSG_HIDE);
//            }
//            handler.sendEmptyMessageDelayed(MSG_HIDE,3000);
//            try {
                if (zhezhao.getVisibility() == View.INVISIBLE) {
//                    handler.removeMessages(MSG_HIDE);
                    zhezhao.setVisibility(View.VISIBLE);
//                    showPreview();
                    stop.setImageResource(R.drawable.newbofangfocus);
                    if (stop.isFocusable()) {
                        stop.requestFocus();
                    }
                } else {
//                    handler.removeMessages(MSG_HIDE);
                    stop.setImageResource(R.drawable.newbofangfocus);
                }
//                if (!AppUtil.STB.Model.equals("E8205") || PRETAG) {
//                    mediaPlayer.pause();
//                    isPlaying = false;
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
            return true;
//        else if (!AppUtil.STB.Model.equals("E8205") && keyCode == 23 && !PRETAG) {
////            if (handler.hasMessages(MSG_HIDE)) {
////                handler.removeMessages(MSG_HIDE);
////            }
////            handler.sendEmptyMessageDelayed(MSG_HIDE,3000);
//            Log.d("ricardo", "click invisible");
//            if (zhezhao.getVisibility() == View.INVISIBLE) {
//                zhezhao.setVisibility(View.VISIBLE);
////                showPreview();
//            } else if (zhezhao.getVisibility() == View.VISIBLE) {
//                zhezhao.setVisibility(View.INVISIBLE);
//            }
//            return true;
//        } else if (AppUtil.STB.Model.equals("E8205") && PRETAG && keyCode == 23
//                && mediaPlayer != null && (!mediaPlayer.isPlaying() || !isPlaying)) {
////            if (handler.hasMessages(MSG_HIDE)) {
////                handler.removeMessages(MSG_HIDE);
////            }
////            handler.sendEmptyMessageDelayed(MSG_HIDE,3000);
//            try {
//                mediaPlayer.start();
//                isPlaying = true;
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            return true;
//        }
        } else if (keyCode==KeyEvent.KEYCODE_MENU && (!mediaPlayer.isPlaying() || !isPlaying)){
//            if (handler.hasMessages(MSG_HIDE)) {
//                handler.removeMessages(MSG_HIDE);
//            }
//            handler.sendEmptyMessageDelayed(MSG_HIDE,3000);
            try {
                isPlaying = true;
                mediaPlayer.start();
                stop.setImageResource(R.drawable.newzangtingfocus);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return true;
        }else if (keyCode==KeyEvent.KEYCODE_DPAD_LEFT && (!AppUtil.STB.Model.equals("E8205") || PRETAG)){
//            if (handler.hasMessages(MSG_HIDE)) {
//                handler.removeMessages(MSG_HIDE);
//            }
//            handler.sendEmptyMessageDelayed(MSG_HIDE,3000);
            try {
                if (zhezhao.getVisibility() != View.VISIBLE) {
                    zhezhao.setVisibility(View.VISIBLE);
//                    showPreview();
                }
//                int currentPosition = (int) mediaPlayer.getCurrentPosition();
//                int totime = 0;
//                if (currentPosition - 2000 <= 0) {
//                    totime = 0;
//                } else {
//                    totime = currentPosition - 2000;
//                }
//                mediaPlayer.seekTo(totime);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return super.onKeyDown(keyCode, event);
        }else if (keyCode==KeyEvent.KEYCODE_DPAD_RIGHT && (!AppUtil.STB.Model.equals("E8205") || PRETAG)){
//            if (handler.hasMessages(MSG_HIDE)) {
//                handler.removeMessages(MSG_HIDE);
//            }
//            handler.sendEmptyMessageDelayed(MSG_HIDE,3000);
//            try {
//                if (zhezhao.getVisibility() != View.VISIBLE) {
//                    zhezhao.setVisibility(View.VISIBLE);
////                    showPreview();
//                }
//                int currentPosition2 = (int) mediaPlayer.getCurrentPosition();
//                mediaPlayer.seekTo(currentPosition2 + 2000);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
            return super.onKeyDown(keyCode, event);
        }else {
            return super.onKeyDown(keyCode, event);
        }

    }


    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        Log.d("ricardo","surfacrcreate");
        if (mediaPlayer==null){
            mediaPlayer = new MediaPlayer();
        }
        try {
//            mediaPlayer.reset();
//            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnCompletionListener(this);
//            mediaPlayer.setOnPreparedListener(this);
            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    Log.d("ShowActivity", "@@@ onError " + what + ", extra " + extra);
                    return false;
                }
            });
            mediaPlayer.setOnInfoListener(new MediaPlayer.OnInfoListener() {
                @Override
                public boolean onInfo(MediaPlayer mp, int what, int extra) {
                    Log.d("ShowActivity", "@@@ onInfo " + what + ", extra " + extra);
                    return false;
                }
            });
            mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
                @Override
                public void onBufferingUpdate(MediaPlayer mp, int percent) {
                    try {
                        handler.sendEmptyMessage(MSG_PROGRESS);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });

            mediaPlayer.setDisplay(holder);
            mediaPlayer.setDataSource(playurl);
//            mediaPlayer.prepareAsync();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Log.d("ShowActivity", "@@@ prepare");
                        mediaPlayer.prepare();
                        Log.d("ShowActivity", "@@@ sendEmptyMessage MSG_PREPARED");
                        handler.sendEmptyMessage(MSG_PREPARED);
                        isPlaying = true;
                    } catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }).start();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeMessages(MSG_STATE);
        handler.removeMessages(MSG_PROGRESS);
        handler.removeMessages(MSG_HIDE);
        handler.removeMessages(MSG_PREPARED);
        handler.removeMessages(MSG_SEEK);
        handler.removeMessages(MSG_FF);
        handler.removeMessages(MSG_BACK);
        if (mediaPlayer!=null){
            mediaPlayer.release();
            mediaPlayer=null;
        }
    }


    @Override
    public void onCompletion(MediaPlayer mp) {
        if(mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer=null;
        }
        finish();

    }

    @Override
    public void onPrepared(MediaPlayer mediaPlayer) {
        PRETAG=true;
        Log.d("ShowActivity","@@@ pre");
        mediaPlayer.start();
        handler.removeMessages(MSG_STATE);
        int duration = mediaPlayer.getDuration();
        int secondtime = duration / 1000;
        int mintime = secondtime / 60;
        int setime = secondtime - mintime * 60;
        totaltime.setText(formatTime(mintime, setime));
        seek.setMax(mediaPlayer.getDuration());
        per = mediaPlayer.getDuration() / 100;
        handler.sendEmptyMessage(MSG_PROGRESS);
        stop.setFocusable(true);
        backward.setFocusable(true);
        speed.setFocusable(true);
    }

    private static String formatTime(int min, int sec) {
        return String.format("%02d", min) + ":" + String.format("%02d", sec);
    }
}
